import ajax from '../utils/ajax';
import $ from '../jquery/jquery.min.js'
const pageData = {
    currentPage: 1,//当前页
    pageSize: 7,//每页显示多少
    pages: 0,//总页数
    total: 0,//总条数
    now: 0//目前在第几条
}
renderThing();
renderThingPages();
//新增物料返回按钮
$(".newMaterial").on("click", ".thingBack", function () {
    $(".target").addClass("active");
    $(".materialAdmin").removeClass("active");
    renderThing();
});
//新增物料保存按钮
$(".newMaterial").on("click", ".thingSave", function () {
    addThing();
    renderThing();
});
//删除物料
$(".materialAdmin ").on("click", ".thingDel", function () {
    const boolean = confirm("确定是否删除数据");
    if (boolean) {
        const _id = $(this).data("id")
        delThing(_id);
    }

});
//修改物料
$(".materialAdmin").on("click", ".thingChange", async function () {
    $("#thing").removeClass("active");
    const _id = $(this).data("id");
    const { result } = await findThing(_id);
    result.map((item, index) => {
        $("#Name").val(`${item.thingName}`);
        $("#Brand").val(`${item.thingBrand}`);
        $("#Type").val(`${item.thingType}`);
        $("#Unit").val(`${item.thingUnit}`);
        $("#Note").val(`${item.thingNote}`);
        $("#sureThing").attr("index", `${item._id}`);
    })

})
//确认修改物料
$("#thing").on("click", "#sureThing", function () {
    const thingName = $("#Name").val();
    const thingBrand = $("#Brand").val();
    const thingType = $("#Type").val();
    const thingUnit = $("#Unit").val();
    const thingNote = $("#Note").val();
    const _id = $("#sureThing").attr("index");
    // console.log(thingName, thingBrand, thingType, thingUnit, thingNote, _id);
    changeThing(thingName, thingBrand, thingType, thingUnit, thingNote, _id);
})
//搜索物料
$("#thingInput").blur(function () {
    renderThing();

})
//切换每页显示
$("#thingSelect").change(function () {
    const text = $(this).val();
    pageData.pageSize = text;
    renderThing();
    renderThingPages();
})
//上一页
$("#thingLast").click(function () {
    if (pageData.currentPage > 1) {
        pageData.currentPage--;
        renderThing();
        renderThingPages();
    }
})
//下一页
$("#thingNext").click(function () {
    if (pageData.currentPage < pageData.pages) {
        pageData.currentPage++;
        renderThing();
        renderThingPages();
    }
})
//点击切换某一页
$("#thingPage").on("click", ".spans", function () {
    const text = $(this).text();
    pageData.currentPage = text;
    renderThing();
    renderThingPages();
})
//点击跳转到某一页
$("#thingJump").blur(function () {
    const val = $("#thingJump").val();
    // console.log(val,pageData.currentPage);
    if (val <= pageData.pages) {
        pageData.currentPage = val;
        renderThing();
        renderThingPages();
    }
})
//点击全选
$('#allChoose').click(function () {
    const value = document.querySelector('#allChoose');
    const inputs = document.querySelectorAll("#addThing [index]");
    if (value.checked) {
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].checked = true;
        }
    } else {
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].checked = false;
        }
    }
})
//确认入库
$('#okBtn').click(async function () {
    const inputs = [...document.querySelectorAll("#addThing [index]")];
    const _id = [];
    inputs.map((item, index) => {
        if (item.checked) {
            _id.push(item.getAttribute("index"));
        }
    })
    const { result } = await findMore(_id);
    if (result.length > 0) {
        result.map((item, index) =>{
            $('#buyerTbody').append(`<tr>
            <td class='thingName'>${item.thingName}</td>
            <td class='thingBrand'>${item.thingBrand}</td>
            <td class='thingType'>${item.thingType}</td>
            <td class='thingUnit'>${item.thingUnit}</td>
            <td class='thingPrice'></td>
            <td class=''thingNum></td>
            <td class='thingNote'>${item.thingNote}</td>
            <td><span class='thingDel' index='${item._id}'>删除</span></td>
            </tr>`)   
        })
        alert('添加成功');
        $("#addThing").addClass("active");
        //取消选中框
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].checked = false;
        }
        document.querySelector('#allChoose').checked = false;

    } else {
        alert('添加失败')
    }

})
//点击取消
$("#closeBtn").click(function () {
    $("#addThing").addClass("active");
})
//点击删除
$('#buyerTbody').on("click", '.thingDel', function () {
    const trs = $(this).parent().parent();
    trs.remove();
    
})
//打开添加材料
$(".addBuyer").on("click", ".put", async function () {
    $("#addThing").removeClass("active");
    //数控库获取的总数据
    const { result } = await getThing();
    // console.log('数据库的数据',result);
    //表层所有的id
    const mainId = $('#buyerTbody span[index]');
    const arrId = [];
    for (let i = 0; i < mainId.length; i++) {
        arrId.push(mainId[i].getAttribute("index"))
    }
    //如果表层有id,里层就不会渲染这条数据
    const html = result.map((item, index) => {
        if (arrId.indexOf(item._id) == -1 && item.thingState==false) {
          return  `<tr>
        <td><input type="checkbox" index='${item._id}'></td>
        <td class='thingName'>${item.thingName}</td>
        <td class='thingBrand'>${item.thingBrand}</td>
        <td class='thingType'>${item.thingType}</td>
        <td class='thingUnit'>${item.thingUnit}</td>
        <td class='thingNote'>${item.thingNote}</td>
        </tr>`
        }
    }).join("");
    $('#addThing tbody').html(html);
})       



//功能区
//添加物料
function addThing() {
    const thingName = $("#thingName").val();
    const thingBrand = $("#thingBrand").val();
    const thingType = $("#thingType").val();
    const thingUnit = $("#thingUnit").val();
    const thingNote = $("#thingNote").val();
   
    ajax({
        url: '/thingList/addThing',
        type: 'get',
        data: {
            thingName, thingBrand,
            thingType, thingUnit,
            thingNote,thingState:false,
            thingState1:false
        },
        success(res) {
            if (res.code == 200) {
                alert("添加成功");
                $("#thingName").val('');
                $("#thingBrand").val('');
                $("#thingType").val('');
                $("#thingUnit").val('');
                $("#thingNote").val('');
                renderThing();
                renderThingPages();
            } else {
                alert('添加失败');
            }
        }
    })
}
//获取物料
function getThing() {
    const value = $("#thingInput").val();
    return new Promise((resolve, reject) => {
        ajax({
            url: '/thingList/getThing',
            type: 'get',
            data: {
                value,
                currentPage: pageData.currentPage,
                pageSize: pageData.pageSize
            },
            success(res) {
                resolve(res);
            }
        })
    })

}
//渲染物料
async function renderThing() {
    const { result } = await getThing();
    if(result){
    const html = result.map((item, index) =>{
        //渲染物料页面列表
        if(item.thingState==false){
            return `<tr>
            <td>1</td>
            <td class='thingName'>${item.thingName}</td>
            <td class='thingBrand'>${item.thingBrand}</td>
            <td class='thingType'>${item.thingType}</td>
            <td class='thingUnit'>${item.thingUnit}</td>
            <td class='thingNote'>${item.thingNote}</td>
            <td><span class='thingChange' data-id='${item._id}'>修改</span> <span class='thingDel' data-id='${item._id}'>删除</span></td>
            </tr>`
        }
    }).join("");
    $('.materialAdmin tbody').html(html);
    //渲染入库页面的列表
    const html1 = result.map((item, index) =>{
        if(item.thingState==false){
            return `<tr>
            <td><input type="checkbox" index='${item._id}'></td>
            <td class='thingName'>${item.thingName}</td>
            <td class='thingBrand'>${item.thingBrand}</td>
            <td class='thingType'>${item.thingType}</td>
            <td class='thingUnit'>${item.thingUnit}</td>
            <td class='thingNote'>${item.thingNote}</td>
            </tr>`
        }
    }).join("");
    $('#addThing tbody').html(html1);
    }
}
//删除物料
function delThing(_id) {
        ajax({
            url: '/thingList/delThing',
            type: 'post',
            data: {
                _id
            },
            success(res) {
                if (res.code == 200) {
                    alert("删除成功");
                    renderThing();
                } else {
                    alert("删除失败");
                }
            }
        })
    
}
//通过ID查找物料
function findThing(_id) {
    return new Promise((resolve, reject) => {
        ajax({
            url: '/thingList/findThing',
            type: 'post',
            data: {
                _id
            },
            success(res) {
                resolve(res)
            }
        })
    })

}
//修改物料
async function changeThing(thingName, thingBrand, thingType, thingUnit, thingNote, _id) {
    ajax({
        url: '/thingList/changeThing',
        type: 'post',
        data: {
            thingName, thingBrand,
            thingType, thingUnit,
            thingNote, _id
        },
        success(res) {
            if (res.code == 200) {
                alert("修改成功");
                $("#Name").val('');
                $("#Brand").val('');
                $("#Type").val('');
                $("#Unit").val('');
                $("#Note").val('');
                renderThing();
            } else {
                alert("修改失败");
            }
        }
    })
}
//渲染页数
async function renderThingPages() {
    const { result, total, pages } = await getThing();
    pageData.pages = pages;
    pageData.total = total;
    var html = "";
    for (let i = 1; i <= pages; i++) {
        html += `<span class='spans'>${i}</span>`
    }
    $("#thingPage").html(html);

    const box = $("#thingPage .spans");
    for (let i = 0; i < box.length; i++) {
        if (box[i].innerText == pageData.currentPage) {
            box[i].style.backgroundColor = "#409EFF";
            box[i].style.color = "white";
        }
    }
}
//通过多ID查询
function findMore(_id) {
    return new Promise((resolve, reject) => {
        ajax({
            url: '/thingList/findMore',
            type: 'post',
            data: { arr: _id },
            success(res) {
                resolve(res)
            }
        })
    })

}
